package cn.edu.gzist.chapter09.service;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class QuartzJobService {
    @Autowired
    private Scheduler scheduler;

    public void addJob(Class<? extends Job> jobClass, String jobName, String jobGroup, String cronExpression, Map<String,Object> jobData) throws SchedulerException {
        JobDetail jobDetail = JobBuilder
                .newJob(jobClass)
                .withIdentity(jobName, jobGroup)
                .storeDurably()
                .build();
        // 设置JobDataMap
        if(jobData != null && !jobData.isEmpty()) {
            jobDetail.getJobDataMap().putAll(jobData);
        }
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("Trigger_"+jobName,jobGroup)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                .build();
        scheduler.scheduleJob(jobDetail, trigger);
    }

    public void updateJobCron( String jobName, String jobGroup, String cronExpression) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName,jobGroup);
        Trigger trigger = scheduler.getTrigger(triggerKey);
        if(trigger != null) {
            CronTrigger newTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                    .build();
            // 重新调度任务
            scheduler.rescheduleJob(triggerKey, newTrigger);
        }
    }
    public void deleteJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
        scheduler.deleteJob(jobKey);
    }
    public void pauseJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
        scheduler.pauseJob(jobKey);
    }
    public void resumeJob(String jobName, String jobGroup) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(jobName,jobGroup);
        scheduler.resumeJob(jobKey);
    }

//    public List<Map<String,Object>> getAllJobs() throws SchedulerException {
//        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
//        for (String groupName : scheduler.getJobGroupNames()){
//            for(JobKey jobKey : scheduler.getJobKeys(GroupMatcher.groupEquals(groupName))){
//                Map<String,Object> jobMap = new HashMap<String,Object>();
//                jobMap.put("jobName",jobKey.getName());
//                jobMap.put("jobGroup",jobKey.getGroup());
//            }
//        }
//    }
}
